const { ipcMain, webContents, BrowserWindow } = require('electron');
const { processMsg } = require('../../biz/baseService/broadService/broadCastServiceImpl')
const EnvContext = require('../../common/context/EnvContext')
const { createAsyncTask } = require('../../common/utils/threadUtil')

const Emitter = require('events');
const { eventNames } = require('process');
const pushEvent = "__PUBLISH_PUSH__"

exports.initBroadcast = function () {
    EnvContext.getInstance().getEmitter().on(pushEvent, broadcast);
    ipcMain.on(pushEvent, (event, eventName, msgInfo) => {
        broadcast(eventName, msgInfo)
    })
}

async function broadcast(eventName, msgInfo) {
    let theMsgInfo = msgInfo
    if (theMsgInfo.broadcast != undefined) {
        return
    }
    theMsgInfo.broadcast = true
    const retMsgInfo = await processMsg(theMsgInfo)
    EnvContext.getInstance().getEmitter().emit(eventName, retMsgInfo)
    webContents.getAllWebContents().map(webContent => {
        // request模式
        createAsyncTask(webContent.send(eventName + theMsgInfo.msgId, retMsgInfo))
        // 广播模式
        createAsyncTask(webContent.send(eventName, retMsgInfo))
    })
}